#!/usr/bin/env python
# -*- coding: utf-8 -*-
# PROJECT_NAME: F:\code\easyofd\test
# CREATE_TIME: 2023-10-18
# E_MAIL: renoyuan@foxmail.com
# AUTHOR: reno
# note:  use demo
import base64
import os
import sys
import types
import logging

from PIL import Image
from PIL.Image import Image as ImageClass

# 设置日志级别，减少输出
logging.basicConfig(level=logging.WARNING)

project_dir = os.path.join(os.path.dirname(os.getcwd()), "easyofd")
pkg_dir = os.path.dirname(os.getcwd())
print(project_dir)
print(pkg_dir)
sys.path.insert(0, project_dir)
sys.path.insert(0, pkg_dir)

from easyofd.ofd import OFD
from easyofd.parser_ofd.ofd_parser import OFDParser


# 为OFDParser类打补丁，修复签名验证问题
def monkey_patch_ofd_parser():
    """修改OFDParser的get_xml_obj方法，跳过签名验证失败的问题"""
    original_get_xml_obj = OFDParser.get_xml_obj
    
    def patched_get_xml_obj(self, label):
        """补丁版本的get_xml_obj方法，不进行断言检查"""
        try:
            return original_get_xml_obj(self, label)
        except AssertionError:
            # 减少日志输出
            # print(f"跳过签名信息中的断言错误: {label}")
            return {}  # 返回空字典代替None，避免后续处理出错
            
    # 应用补丁
    OFDParser.get_xml_obj = patched_get_xml_obj
    
    # 修改parser方法，防止签名验证失败
    original_parser = OFDParser.parser
    
    def patched_parser(self):
        """补丁版本的parser方法，确保即使签名验证失败也能成功解析"""
        try:
            return original_parser(self)
        except Exception as e:
            # 减少日志输出
            # print(f"解析过程中出现错误，尝试修复: {e}")
            # 确保至少返回基本结构，避免None错误
            if not hasattr(self, 'data') or self.data is None:
                # print("初始化基本数据结构")
                self.data = {
                    "Document": {},
                    "DocBody": {},
                    "CommonData": {},
                    "PublicRes": {},
                    "DocumentRes": {},
                    "Annotations": {},
                    "CustomTags": {},
                    "attachments": {},
                    "signatures_info": {}
                }
            return self.data
    
    OFDParser.parser = patched_parser


# 应用补丁
monkey_patch_ofd_parser()


def test_img2(dir_path):
    """
    jpg2ofd 
    jpg2pfd
    """
    # img_path = os.path.join(".", r"test\Doc_0\Res") # 多页排序问题
    imgs_p = os.listdir(dir_path)
    imgs = []
    for img_p in imgs_p:
        imgs.append(Image.open(os.path.join(dir_path, img_p)))  # 传入改为pil
    ofdbytes = OFD().jpg2ofd(imgs)
    pdfbytes = OFD().jpg2pfd(imgs)
    with open(r"img2test.pdf", "wb") as f:
        f.write(pdfbytes)
    with open(r"img2test.ofd", "wb") as f:
        f.write(ofdbytes)


def test_ofd2(file_path, convert_to_img=False):
    """
    ofd2pdf
    ofd2img (可选)
    
    参数:
        file_path: OFD文件路径
        convert_to_img: 是否同时转换为图片，默认为False，只转换PDF
    """

    file_prefix = os.path.splitext(os.path.split(file_path)[1])[0]
    with open(file_path, "rb") as f:
        ofdb64 = str(base64.b64encode(f.read()), "utf-8")
    
    ofd = OFD()  # 初始化OFD 工具类
    
    try:
        ofd.read(ofdb64, save_xml=False)  # 读取ofdb64，不保存XML文件减少输出
    except Exception as e:
        print(f"OFD解析出错: {e}")
    
    try:
        # 转换PDF
        pdf_bytes = ofd.to_pdf()
        
        # 写入PDF文件
        output_pdf = f"{file_prefix}.pdf"
        with open(output_pdf, "wb") as f:
            f.write(pdf_bytes)
            
        print(f"已成功转换并保存PDF文件: {output_pdf}")
        
        # 是否需要转换图片
        if convert_to_img:
            img_np = ofd.to_jpg()
            for idx, img in enumerate(img_np):
                output_img = f"{file_prefix}_{idx}.jpg"
                img.save(output_img)
            print(f"已成功转换并保存图片文件")
    except Exception as e:
        print(f"转换过程中出错: {str(e)}")
    finally:
        ofd.del_data()


def test_pdf2(file_path):
    """
    pdf2ofd
    pdf2img
    """
    file_prefix = os.path.splitext(os.path.split(file_path)[1])[0]
    with open(file_path, "rb") as f:
        pdfb64 = f.read()
    ofd = OFD()
    ofd_bytes = ofd.pdf2ofd(pdfb64, optional_text=False)  # 转ofd # optional_text 生成可操作文本 True 输入也需要可编辑pdf
    img_np = ofd.pdf2img(pdfb64)
    ofd.del_data()
    with open(f"{file_prefix}.ofd", "wb") as f:
        f.write(ofd_bytes)
    for idx, img in enumerate(img_np):
        img.save(f"{file_prefix}_{idx}.jpg")


if __name__ == "__main__":
    file_path = rf"input_files\2025年银行明细——蒙兴建行梅苑路5月对账单.ofd"
    
    # 默认只转换PDF，不转图片
    test_ofd2(file_path)
    
    # 如果需要同时转换图片，可以使用：
    # test_ofd2(file_path, convert_to_img=True)
    
    # # file_path = r"data/2.ofd"
    # if len(sys.argv) > 1:
    #     if sys.argv[1] == "ofd2":
    #         test_ofd2(file_path)
    #     elif sys.argv[1] == "pdf2":
    #         test_pdf2(file_path)
    #     elif sys.argv[1] == "img2":
    #         test_img2(file_path)
    #     else:
    #         test_ofd2(file_path)
    # else:
    #     test_ofd2(file_path)